<template>
  <div>
    <div>
      <el-row style="margin: 10px" :gutter="2">
        <el-col span="4">
          <el-input
            v-model="selectForm.patentName"
            placeholder="请输入专利名称"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col span="1">
          <el-button type="primary" @click="this.getPatenInfo(this.pageNum)"
            >搜索</el-button
          >
        </el-col>

        <el-col span="2">
          <PatentInfoAdd></PatentInfoAdd>
        </el-col>
        <el-col span="3" :push="15">
          <el-button round @click="searchCollapseShowFun()"
            ><el-icon><search /></el-icon>高级检索</el-button
          >
        </el-col>
      </el-row>
    </div>

    <!-- 高级检索 -->
    <div>
      <!-- 折叠面板 -->
      <el-collapse class="searchHead" v-model="showSearch">
        <el-collapse-item name="search">
          <template #title
            ><el-icon size="15px"><Search /></el-icon
            >&nbsp;&nbsp;&nbsp;高级检索</template
          >
          <!-- 表单数据排版 -->
          <el-form ref="selectForm">
            <!-- 第一行 -->
            <el-row :gutter="56">
              <el-col :offset="2" :span="4">
                <el-form-item label="专利类别">
                  <el-input v-model="selectForm.patentType" />
                </el-form-item>
              </el-col>
              <el-col :span="4"
                ><el-form-item label="专利名称">
                  <el-input v-model="selectForm.patentName" /> </el-form-item
              ></el-col>
              <el-col :span="4"
                ><el-form-item label="第一单位名称"
                  ><el-input v-model="selectForm.firstUnit" /></el-form-item
              ></el-col>
              <el-col :span="4"
                ><el-form-item label="其他单位名称"
                  ><el-input v-model="selectForm.otherUnit" /></el-form-item
              ></el-col>
              <el-col :span="4"
                ><el-form-item label="专利人"
                  ><el-input v-model="selectForm.person" /></el-form-item
              ></el-col>
            </el-row>

            <!-- 第二行 -->
            <el-row :gutter="56">
              <el-col :span="4" :offset="2">
                <el-form-item label="基金支持号">
                  <el-input v-model="selectForm.projectNum" />
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="本人所属单位">
                  <el-input v-model="selectForm.unitSelf" />
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="基金支持项目">
                  <el-input v-model="selectForm.projectId" />
                </el-form-item>
              </el-col>

              <el-col :span="10">
                <el-form-item label="专利获得日期">
                  <template style="display: flex">
                    <el-date-picker
                      placeholder="起始时间"
                      style="width: 150px"
                      v-model="selectForm.publishDateBeg"
                    />
                    <span>&nbsp;&nbsp;&nbsp;--&nbsp;&nbsp;&nbsp;</span>
                    <el-date-picker
                      placeholder="结束时间"
                      style="width: 150px"
                      v-model="selectForm.publishDateEnd"
                    />
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-button @click="this.getPatenInfo(this.pageNum)"
                >查询</el-button
              >
              <el-button
                @click="
                  this.selectForm = {};
                  this.getPatenInfo(this.pageNum);
                "
                >清空</el-button
              >
            </el-row>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      border="true"
      max-height="65vh"
      height="65vh"
      v-loading="loading"
      element-loading-text="Loading..."
      :default-sort="{ prop: 'publishDate', order: 'descending' }"
    >
      <template #empty>
        <el-empty description="未查询到数据"></el-empty>
      </template>
      <el-table-column
        type="index"
        label="序号"
        width="50px"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="patentTypeStr"
        label="专利类别"
        width="130px"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="patentName"
        label="专利名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="publishDate"
        label="专利获得日期"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="firstUnit"
        label="第一单位名称"
        align="center"
      ></el-table-column>

      <el-table-column label="基金支持项目" align="center">
        <template #default="scope">
          <template v-if="scope.row.projectId == '其他项目'">{{
            scope.row.projectName
          }}</template>
          <template v-else>{{ scope.row.projectId }}</template>
        </template>
      </el-table-column>

      <el-table-column prop="" label="操作" align="center">
        <template #default="scope">
          <el-button-group>
            <el-button
              type="primary"
              @click="detailInfo(scope.row.id)"
              :disabled="!this.hasAuth('sys:patent:detail')"
              >详情</el-button
            >
            <el-button
              type="primary"
              @click="updata(scope.row.id)"
              :disabled="
                !this.hasAuth('sys:patent:detail') ||
                !this.hasAuth('sys:patent:update')
              "
              >修改</el-button
            >
            <el-button
              type="danger"
              @click="delectInfo(scope.row.id)"
              :aria-disabled="!this.hasAuth('sys:patent:delete')"
              >删除</el-button
            >
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      v-model:currentPage="currentPage"
      :page-size="10"
      layout="total,prev, pager, next, jumper"
      :total="total"
      @current-change="handleCurrentChange"
      background="true"
    >
    </el-pagination>

    <!-- 详情 -->
    <el-dialog v-model="dialogTableVisible" top="5vh">
      <el-scrollbar height="700px">
        <el-descriptions direction="horizontal" :column="1" border>
          <el-descriptions-item label="专利类别">{{
            detailData.patentTypeStr
          }}</el-descriptions-item>
          <el-descriptions-item label="专利名称">{{
            detailData.patentName
          }}</el-descriptions-item>
          <el-descriptions-item label="专利获得日期">{{
            detailData.publishDate
          }}</el-descriptions-item>
          <el-descriptions-item label="第一单位名称">{{
            detailData.firstUnit
          }}</el-descriptions-item>
          <el-descriptions-item label="其他单位">{{
            detailData.otherUnit
          }}</el-descriptions-item>
          <el-descriptions-item label="专利人">{{
            detailData.person
          }}</el-descriptions-item>
          <el-descriptions-item label="基金支持号">{{
            detailData.projectNum
          }}</el-descriptions-item>
          <el-descriptions-item label="基金支持项目">
            <template v-if="detailData.projectId == '其他项目'">
              {{ detailData.projectName }}
            </template>
            <template v-else>
              {{ detailData.projectId }}
            </template>
          </el-descriptions-item>
          <el-descriptions-item
            label="附件"
            v-if="detailData.utilFiles.length > 0"
          >
            <template v-for="data in detailData.utilFiles" :key="data.id">
              <a
                :href="
                  'http://101.43.150.171:8082/PatentInfo/downLoad?fileName=' +
                  data.utilName +
                  '&fileNameSrc=' +
                  data.utilSrcName +
                  '&parameter=' +
                  token
                "
              >
                {{ data.utilSrcName }}
              </a>
              <br />
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </el-scrollbar>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog v-model="dialogFormToUp" title="修改" top="5vh">
      <el-scrollbar height="700px">
        <el-form
          ref="detailData"
          :model="detailData"
          label-width="120px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item label="专利类别" prop="patentType">
            <el-select v-model="detailData.patentType" style="width: 100%">
              <el-option
                v-for="item in patentType"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专利名称" prop="patentName">
            <el-input v-model="detailData.patentName" type="text"></el-input>
          </el-form-item>
          <el-form-item label="专利获得日期" prop="publishDate">
            <el-date-picker
              style="width: 100%"
              v-model="detailData.publishDate"
              type="date"
              placeholder="专利获取时间"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="第一单位名称" prop="firstUnit">
            <el-autocomplete
              v-model="detailData.firstUnit"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入本人所属单位"
              @select="handleSelectFirstUnit"
              value-key="companyName"
              :trigger-on-focus="false"
              style="width:100%"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="其他单位" prop="otherUnit">
            <el-autocomplete
              v-model="detailData.otherUnit"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入本人所属单位"
              @select="handleSelectOtherUnit"
              value-key="companyName"
              :trigger-on-focus="false"
              style="width:100%"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="专利人" prop="person">
            <el-input v-model="detailData.person" type="text"></el-input>
          </el-form-item>
          <el-form-item label="基金支持号" prop="projectNum">
            <el-input v-model="detailData.projectNum" type="text"></el-input>
          </el-form-item>
          <el-form-item label="基金支持项目" prop="projectId">
            <el-select
              v-model="detailData.projectId"
              style="width: 100%"
              @change="this.detailData.projectName = ''"
            >
              <el-option
                v-for="item in projectList"
                :key="item.projectName"
                :label="item.projectName"
                :value="item.projectName"
              ></el-option>
              <el-option label="其他项目" value="其他项目" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-show="detailData.projectId == '其他项目'"
            label="基金支持项目"
            prop="projectName"
          >
            <el-input
              v-model="detailData.projectName"
              placeholder="请输入其他基金支持项目名称"
            />
          </el-form-item>

          <el-form-item label="添加附件" prop="file">
            <el-upload
              class="upload-demo"
              :before-remove="beforeRemove"
              :on-change="fileChangeFunc"
              drag
              action=""
              multiple
              name="file"
              style="float: left"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-icon class="el-icon--upload"><Document /></el-icon>
              <div class="el-upload__text">
                拖放文件上传 或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  单个文件最大为50MB,总上传大小为100MB
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('detailData')"
              >修改</el-button
            >
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import axios from "../../utils/request";
import { ElNotification } from "element-plus";
import PatentInfoAdd from "./patentInfoAdd.vue";
import { Search, Document } from "@element-plus/icons";
export default {
  components: { PatentInfoAdd, Search, Document },
  inject: ["reload"], //页面刷新函数
  data() {
    return {
      dialogTableVisible: false, //详情弹窗
      dialogFormToUp: false, //修改弹窗
      tableData: [],
      total: "",
      detailData: { projectName: "" },
      selectForm: {},
      currentPage: 1,
      pageSize: 10,
      pageNum: 1,
      loading: false,
      fileList: [],
      files: [],
      searchSenior: false,
      showSearch: "",
      // 表单校验规则
      rules: {
        patentType: [
          { required: true, message: "该字段不允许为空", trigger: "change" },
        ],
        patentName: [
          { required: true, message: "该字段不允许为空", trigger: "change" },
        ],
        publishDate: [
          {
            required: true,
            validator: this.checkPublishDate,
            trigger: "change",
          },
        ],
        firstUnit: [
          { required: true, message: "该字段不允许为空", trigger: "change" },
        ],
        otherUnit: [
          { required: true, message: "该字段不允许为空", trigger: "change" },
        ],
        person: [
          { required: true, message: "该字段不允许为空", trigger: "change" },
        ],
        projectNum: [
          { required: true, message: "该字段不允许为空", trigger: "change" },
        ],
        projectId: [
          { required: true, message: "该字段不允许为空", trigger: "change" },
        ],
        projectName: [
          {
            required: true,
            validator: this.checkProjectName,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    /**
     * 表单数据校验规则
     */
    checkProjectName(rule, value, callback) {
      if (this.detailData.projectId != "其他项目") {
        callback();
      } else {
        if (value == null || value == "") {
          callback(new Error("该字段不允许为空"));
        } else {
          callback();
        }
      }
    },
    checkPublishDate(rule, value, callback) {
      let nowDate = new Date();
      let publishDate = new Date(value);
      if (publishDate > nowDate) {
        callback(new Error("不允许大于当前时间"));
      } else {
        callback();
      }
    },
    /**
     * 功能函数
     */
    searchCollapseShowFun() {
      this.searchSenior = !this.searchSenior;
      if (this.searchSenior) {
        this.showSearch = "search";
      } else {
        this.showSearch = "";
      }
    },
    detailInfo(id) {
      console.log(id);

      axios({
        method: "get",
        url: "/PatentInfo/detail",
        params: {
          id: id,
        },
      }).then((reponse) => {
        this.dialogTableVisible = true;
        this.detailData = reponse.data.data.patentInfo;
        // console.log(this.detailData)
      });
    },
    delectInfo(id) {
      // alert("删除id"+id)
      axios({
        method: "get",
        url: "/PatentInfo/delete",
        params: {
          id: id,
        },
      }).then((reponse) => {
        if (reponse.data.status === 200) {
          ElNotification({
            message: reponse.data.message,
            type: "success",
          });
          this.getPatenInfo(this.currentPage);
        }
      });
    },
    updata(id) {
      this.fileList = [];
      axios({
        method: "get",
        url: "/PatentInfo/detail",
        params: {
          id: id,
        },
      }).then((reponse) => {
        this.dialogFormToUp = true;
        this.detailData = reponse.data.data.patentInfo;
        for (
          var i = 0;
          i < reponse.data.data.patentInfo.utilFiles.length;
          i++
        ) {
          this.fileList.push({
            id: reponse.data.data.patentInfo.utilFiles[i].id,
            name: reponse.data.data.patentInfo.utilFiles[i].utilSrcName,
            isExcite: true, //服务器中是否存在
          });
        }
      });
    },
    submitForm(val) {
      this.$refs[val].validate((valid, obj) => {
        console.log(obj);
        if (valid) {
          var formData = new window.FormData();
          formData.append(
            "patentInfo",
            new Blob([JSON.stringify(this.detailData)], {
              type: "application/json",
            })
          );
          if (this.files.length != 0) {
            this.files.forEach((data) => {
              formData.append("files", data.raw);
            });
          }
          axios.post("/PatentInfo/upData", formData).then((res) => {
            if (res.data.status === 200) {
              ElNotification({
                message: res.data.message,
                type: "success",
              });
            }
            this.dialogFormToUp = false;
            this.getPatenInfo(this.currentPage);
          });
        } else {
          return false;
        }
      });
    },
    getPatenInfo(pageNum) {
      this.loading = true;
      axios
        .post(
          "/PatentInfo/searchPatentInfo/" + pageNum + "/" + this.pageSize,
          this.selectForm
        )
        .then((reponse) => {
          this.tableData = reponse.data.data.patentPageInfo.list;
          this.total = reponse.data.data.patentPageInfo.total;
          this.loading = false;
        });
    },
    handleCurrentChange(val) {
      this.getPatenInfo(this.currentPage);
      this.currentPage = val;
    },
    hasAuth(perm) {
      var authority = this.$store.state.menus.permList;
      return authority.indexOf(perm) > -1;
    },
    // 表单文件上传函数
    beforeRemove(file, fileList) {
      console.log(fileList);
      // var re = this.$confirm(`确定将文件 ${file.name}从服务器中删除?`);
      if (file.isExcite === true) {
        axios
          .get("/UtilFiles/delete", { params: { id: file.id } })
          .then((res) => {
            ElMessage.success("文件" + res.data.message);
          });
      } else {
        //删除上传列表中数据
        this.files.splice(this.files.indexOf(file), 1);
      }
    },
    fileChangeFunc(file, fileList) {
      // console.log("file :",file);
      this.files.push(file);
      console.log("fileList:", fileList);
    },
    getPatentType() {
      axios.get("/patentTypeList").then((res) => {
        this.patentType = res.data.data.patentType;
      });
    },
    //获取项目列表
    getProjectList() {
      axios.get("/ProjectInfo/projectList").then((res) => {
        this.projectList = res.data.data.projectList;
      });
    },

    /**
     * 单位信息输入建议
     */
    //获取单位信息
    getCompanyInfo() {
      axios.get("/CompanyInfos/searchInput").then((res) => {
        // console.log(res);
        this.restaurants = res.data.data.map_companyInfo;
      });
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      cb(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.companyName.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelectFirstUnit(item) {
      this.detailData.firstUnitId = item.id;
    },
    handleSelectOtherUnit(item) {
      this.detailData.otherUnitId = item.id;
    }
  },
  mounted() {
    //数据获取 —— 项目
    this.getPatenInfo(this.pageNum);
    this.getPatentType();
    this.getProjectList();
    this.getCompanyInfo();
  },
  computed: {
    token: {
      get() {
        return localStorage.getItem("token");
      },
    },
  },
};
</script>
